2013-05-10 57 views
0

我想映射所有的URL如/ home/user中或/首頁/或/首頁/註冊或者......像這樣的C#頁:如何將所有操作映射到C#類而不是ASP?

例如User.cs頁是這樣的:

public class User 
{ 
    public string run(UrlParameter id){ 
     return "Hello World"; 
    } 
} 

我希望當用戶發送/家庭/用戶的請求..調用用戶類的運行功能,並顯示返回值給用戶。我怎麼能在ASP MVC中做到這一點?

我可以在RouteConfig中更改路線嗎?現在我目前的MVC的路線是:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(
     name: "Default", 
     url: "{controller}/{action}/{id}", 
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 
} 

,當我打電話一些URL方案運行在視圖文件夾中的ASP頁面,在C#.NET MVC項目的默認值。

詳細解釋:

我有我的客戶端和服務器端程序,它是JSON之間的協議。我希望返回字符串JSON時,客戶端要求的東西和做到這一點,我不需要asp頁面呈現HTML,我只需要調用一些函數,返回JSON到客戶端。

我怎麼用MVC做到這一點?

+1

除非我想你的問題,否則我認爲你對MVC的工作原理有一個根本的誤解。 – 2013-05-10 16:13:22

+0

真的我的客戶端程序全部用javascript工作,而且我想從我的所有服務器頁面中獲得JSON,這些都會給我的javascript ..現在該怎麼辦?我不需要asp或cshtml頁面,我只需要一些函數爲每個頁面中的每個動作返回json。 – 2013-05-10 16:16:15

+0

對不起我的英文 – 2013-05-10 16:17:38

回答

1

我假設你的問題有兩個部分。

第一部分:將網址映射到頁面。某種意義上,這是什麼是路由。它將url映射到動作,該動作可以是頁面,也可以是圖片之類的資源,或JSON數據等響應。注意它並不總是一個頁面,通常一個url映射到資源

讀取URL路由文檔here

routes.MapRoute(
     name: "Default", 
     url: "/Page1", 
     defaults: new { controller = "Home", action = "Page1", 
       id = UrlParameter.Optional } 
); 

在上面的例子:fakedomain.com/Page1將在HomeController類運行Page1方法,如果沒有你所添加的任何代碼那麼它將在您的視圖文件夾內搜索Page1.aspxPage1.cshtml

我會建議在這一點上閱讀關於REST。我建議這篇文章:How I explained REST to my wife


對於你的第二部分:你如何返回JSON數據。那麼你使用WebApi。請參閱文檔here.

WebApi允許您編寫基於請求返回數據的控制器。因此,如果您的客戶端發送Ajax請求並將接受頭設置爲application/json,則WebApi將返回JSON。

它也遵循asp.net-MVC控制器,路由和動作的典型系統。

所以返回JSON數據表示產品你將有一個ProductController的,看起來像這樣:

public class ProductsController : ApiController 
{ 

    Product[] products = new Product[] 
    { 
     new Product { Id = 1, Name = "Tomato Soup", 
         Category = "Groceries", Price = 1 }, 
     new Product { Id = 2, Name = "Yo-yo", 
         Category = "Toys", Price = 3.75M }, 
     new Product { Id = 3, Name = "Hammer", 
         Category = "Hardware", Price = 16.99M } 
    }; 

    public IEnumerable<Product> GetAllProducts() 
    { 
     return products; 
    } 

    public Product GetProductById(int id) 
    { 
     var product = products.FirstOrDefault((p) => p.Id == id); 
     if (product == null) 
     { 
      throw new HttpResponseException(HttpStatusCode.NotFound); 
     } 
     return product; 
    } 
} 

與ASP。淨mvc4和默認路由設置爲的WebAPI上述控制器將以下網址

This would get all products 
/api/products/ 
This would get call the GetProductById and return ONE product: 
/api/products/put_id_here 

我會強烈建議讓所有的先決條件如Visual Studio和asp.net-MVC從Web Platform installer然後follow this tutorial迴應。

+0

非常感謝吉迪恩,感謝Daniel A. White&Dave A向我介紹WebApis – 2013-05-10 16:46:27

相關問題