开发者

Strongly typed API for ASP.NET MVC 2 async actions

Have anybody tried to create strongly开发者_运维问答 typed API for ASP.NET MVC 2 async actions?

Best regards, Alexey Zakharov


I believe we have recently done something like this if I've understood you correctly. We used the JsonValueProviderFactory from the ASP.NET MVC 2 Futures library to achieve the strongly typed action (more info on this on haaked.com).

For the async action we have something similar to this:

[HandleError]
public class HomeController : AsyncController
{
    [HttpPost]
    public void IndexAsync(Person person)
    {
        DoSomething();
    }

    public ActionResult IndexCompleted()
    {
        return View();
    }
}

public class Person
{
    public string Forename { get; set; }
    public string Surname { get; set; }
}

and just make a POST to the action with:

{"Forename": "Cheesy", "Surname": "Goat"}

There is a great Firefox plug-in to help with testing this called 'REST Client' that I would recommend also.

Hope this helps.


MVC could well do this but my understanding from the code sample you have provided is that you want a json based API.

Microsoft created WebAPI for exactly this situation, it's both strongly typed and follows the MVC pattern in its underlying design, but it also works well and can be used along side MVC within the same web application.

However:

If you want to you can provide serialised objects from an MVC controller action using a simple Json serialiser package and simply returning the resulting string, ActionResult supports this scenario too, and for posts use the built in metadata infrastructure to validate your type specific data from the post giving you your desired type safety.

Treating the MVC controller like a rest endpoint is also possible its just a matter of contructing the controller in the right fashion to support typical REST calls.

I would however strongly recommend using WebAPI for this as it is the better fit for API scenarios.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜