ASP.Net WebApi: Invalid URL generated in BeginForm

2019-08-30 02:49发布

I'm beginning to use WebApi and I'm having an issue with a URL being incorrectly generated

I have an ApiController like this:

public class EntriesController : ApiController
{
    public HttpResponseMessage Post(Entry entry)
    {
    ...
    }
}

And I was trying to create a standard controller (i.e. not webapi) in the same project to test this api (I already tested the api with fiddler and everything is ok there).

I assumed I could use the standard HTML helpers like this:

@using (Html.BeginForm("Post", "Entries"))

However this generates the following markup:

<form action="/Entries/Post" method="post">

and I expected it to generate

<form action="/api/Entries" method="post">

What is the correct way to generate the API url from a view?

I am using the default api and controller routes.

Thanks

3条回答
家丑人穷心不美
2楼-- · 2019-08-30 03:16

You would need to use BeginRouteForm as link generation to Web API routes always depends on the route name. Also make sure to supply the route value called httproute as below.

@using (Html.BeginRouteForm("DefaultApi", new { controller="Entries", httproute="true" }))

查看更多
爷、活的狠高调
3楼-- · 2019-08-30 03:27

This is technically possible by doing:

@using (Html.BeginForm("Post", "api/Entries"))

Don't forget, the "Post" value in the .BeginForm() extension method doesn't mean anything to an out-of-box Web Api route setup. Only the url and HTTP action matter (and any additional values on the URL for method overloading)

查看更多
我命由我不由天
4楼-- · 2019-08-30 03:31
@using (Html.BeginForm("Post", "Entries"))

You can not put WebAPI controller and method in MVC BeginForm like above. You need to pass MVC Controller and action to the BeginForm.

You can create a WebAPI EntriesController instance in your MVC controller, then use this instance to call the WebAPI method. See below:

//MVC Controller
public class EntriesController : Controller
{
    [HttpGet]
    public ActionResult Entries()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Entries(SomeModels model)
    {
        if (ModelState.IsValid)
        {
            var api = new EntriesController(); // Create WebAPI instance Here
            api.Post(model.entry);

            return RedirectToAction("Index", "Home");
        }
        return View();
    }
}
查看更多
登录 后发表回答