【问题标题】:How to set url as webapi in the .net core web?如何在.net core web 中将 url 设置为 webapi?
【发布时间】:2019-12-29 18:29:12
【问题描述】:

在 Web 应用程序中,我创建了一个 Page:DetailPage

public void OnGet(int id)
{
    var bll = new BLL.Articles();
    Item = bll.GetModel(id);
    if (Item == null)
    {
        RedirectToPage("Blogs");
    }
}

网址是

localhost/Detail?id=1

我可以将其设为 Web API URL,例如 `

localhost/Detail/1

我添加了[HttpGet("id")],但没有按预期工作。

【问题讨论】:

标签: .net asp.net-core asp.net-core-2.0 razor-pages


【解决方案1】:

由于 @Nkosi 在 cmets 中提供了正确的 document,您必须修改 Startup.cs

像这样改变ConfigureServices方法:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_0)
.AddRazorPagesOptions(options =>
{
    options.Conventions.AddPageRoute("/Detail", "Detail/{id}");
});

现在实现您的标准视图

@page
@model Item

<p>@Model.[property]</p>

【讨论】:

  • [属性] 是什么意思? cs文件中的一样吗?
  • 你之前在Item对象中声明的@daotian属性。比如IdNameModifiedDate...。 Item 是您在此行中使用的:Item = bll.GetModel(id);
【解决方案2】:

您可以将其添加到您的 *.cshtml 页面的顶部:

@page "{id:int}"

然后在您的详细信息页面中:

public void OnGet([FromRoute] int id)

无需修改您的Startup.cs 文件。

【讨论】:

  • 谢谢@crgolden,但只有 int 可以 {id:string} 不起作用
  • string 是默认的,所以在这种情况下你可以使用@page(没有绑定)
  • 好吧,在这种情况下它工作得很好,但我个人认为通过在一个地方声明所有剃须刀选项更优雅,你也可以完全控制路由options.Conventions.AddPageRoute("/Detail", "alias/{id}");
  • @Masoud Keshavarz 当您修改您的Startup.cs 时,您将您的页面与特定的应用程序实现紧密耦合。如果需要,这使得很难将它们分离到可重用的 Razor 类库中。如果页面很多,您的Startup.cs 也会有很多硬编码字符串。
  • @crgolden 如果只有@页面那么[FromRoute]也需要?
猜你喜欢
  • 1970-01-01
  • 2019-10-21
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多