ASP.NET Core Url.Action return empty string

本秂侑毒 提交于 2019-12-24 07:38:38

问题


After 3 hours browsing on stackoverflow I don't find solution of my problem. So I suspect something in my project is special.

I have a ASP.NET Core (2.0) WebApplications Project on Visual Studios 2017. I try to make a ajax call from my Kalender.cshtml file:

return $.ajax({
    type: 'GET',
    url: myurl,
    data: '{}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {        //REQUEST SUCCESS
        alert(result);
    },

with myurl:

var myurl = '@Url.Action("EventsRead","Kalender")';

but I recognize that alert(myurl) return an empty string. So the ajax call must fail. I guess the url should something like:

/Kalender/EventsRead

but if I use this, ajax return 404 Not found.

My Kalender.cshtml.cs Action looks like:

[HttpGet]
public IActionResult EventsRead()
{
    //DATABASE READOUT        
    var events = DataBase.Events.ToList();
    return new JsonResult(events);
}

And the class of the PageModel looks like:

public class KalenderModel : PageModel

Here is everything auto generated. I try about 100 different version but never get a breakpoint into the EventsRead() action.

SIDE INFORMATION:

In my Startup.cs I suppress AntiforgeryToken:

services.AddMvc().AddRazorPagesOptions(options =>
{
    options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
});

I really need some help before I get insane, thankful for any response. Martin


回答1:


Everybody who interested into the solution:

I changed in Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //ROUTES DEFAULT SETTINGS
        app.UseMvc();
    }

to:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //ROUTES CUSTOM SETTINGS
        app.UseMvcWithDefaultRoute();
    }

after this

'@Url.Action("TestGet","Kalender")'

will return correkt path.

Now I go to my bed and cry.




回答2:


Your Controller setup looks just fine. When you used /Kalender/EventsRead as url and have a response 404 because of your data field. You've put curly braces as string. Try this in your ajax call

return $.ajax({
    type: 'GET',
    url: '/Kalender/EventsRead',
    data:{},
    success: function (result) {        //REQUEST SUCCESS
        console.log(result);
    },
    error: function (response){
        console.log(response)
    });

This may help you.



来源:https://stackoverflow.com/questions/49893730/asp-net-core-url-action-return-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!