如何在DOTNET CORE中使用C#提交HTTP表单

时间:2019-06-20 12:52:52

标签: c# .net-core asp.net-core-webapi asp.net-core-2.1

我已经使用c#字符串生成器创建了HTML表单,其引用为:https://stackoverflow.com/a/37757601/7961948

在dotnet中,我们可以使用

提交此表单
Response.Write(formPostText);

但是现在我正在使用DOTNET CORE 2.1 并且DOTNET CORE不支持dotnet功能 因此,还有其他方式可以提交表单

示例代码: 在dotnet版本上工作

     var formPostText = @"<html><body><div>
    <form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
      <input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" /> 
      <input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" /> 
    </form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
    ";

Response.Write(formPostText);

2 个答案:

答案 0 :(得分:0)

不清楚是使用MVC还是Web API,但无论哪种情况,在考虑如何使用ModelState验证来验证表单输入时,最好查看以下资源:

方法通常是相同的,但是有所不同。

关于存储在formPostText中的HTML,是否有任何理由要使用字符串构建表单?我建议使用视图,因为这样可以更好地将表示层与逻辑层分开。如果必须生成原始HTML内容,则可以执行以下操作:

private string GetViewHtml(FormViewModel model)
{
    return this.RenderView("/Views/Shared/FormView.cshtml", model);
}

在此示例中,该示例是为MVC 5构建的,RenderView是控制器的扩展方法:

public static class ControllerExtensions
{
    public static string RenderView(this System.Web.Mvc.Controller controller, string viewName, object model)
    {
        return RenderView(controller, viewName, new ViewDataDictionary(model));
    }

    public static string RenderView(this System.Web.Mvc.Controller controller, string viewName, ViewDataDictionary viewData)
    {
        var controllerContext = controller.ControllerContext;

        var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);

        StringWriter stringWriter;

        using (stringWriter = new StringWriter())
        {
            var viewContext = new ViewContext(
                controllerContext,
                viewResult.View,
                viewData,
                controllerContext.Controller.TempData,
                stringWriter);

            viewResult.View.Render(viewContext, stringWriter);
            viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
        }

        return stringWriter.ToString();
    }
}

答案 1 :(得分:0)

Dotnet核心支持

var s = "some html / html form";

HttpContext.Response.WriteAsync(s.ToString());

查找参考信息: https://gist.github.com/priore/7163408

Is there an equivalent to "HttpContext.Response.Write" in Asp.Net Core 2?