如何获得响应的状态,而我们提交一个表单的Web API [英] How to get a Response status while we submit a form to Web API

查看:145
本文介绍了如何获得响应的状态,而我们提交一个表单的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户端的HTML应用程序和Asp.net的WebAPI作为服务器应用程序。
我有一个场景,我不得不做出一个表单提交和表单的一部分提交我需要的表单数据发布到数据库中。这是为我工作,但客户端应用程序怎么能知道这是在不同领域发生的DB操作的成功或失败状态。我试图的Htt presponseMessage 对象返回给客户端,但我的整个HTML页面得到了与我从服务器返回的状态重写。
有没有这种检查特定的状态之中,而不是重写从服务器API应用程序得到响应整个HTML,这样我将在客户端应用程序更多的控制有办法?

客户端code代表提交表单:

 函数ValidateFileAndSubmit(){
        VAR myForm会= $(#Form1的);
        //上传文件();
        VAR rootServicePath = config.rootURL;
        VAR路径= rootServicePath +'API /上传/ UploadFile';        myForm.attr('行动,路径);
        myForm.submit();    }

网页API code,其中我进入POST调用:

  [HttpPost]
    公众的Htt presponseMessage UploadFile()
    {
        HTT presponseMessage响应= NULL;
        如果(HttpContext.Current.Request.Files.AllKeys.Any())
        {
            HttpContext.Current.Response.ContentType =text / html的;
            VAR httpPostedFile = HttpContext.Current.Request.Files [UploadedImage];            如果(httpPostedFile!= NULL)
            {                //验证上传的图片(可选)                //获取完整的文件路径
                变种fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath(〜/ UPLOADEDFILES),httpPostedFile.FileName);                //保存上传的文件为UPLOADEDFILES文件夹中
                httpPostedFile.SaveAs(fileSavePath);                响应=新的Htt presponseMessage(的HTTPStatus code.Created)
                {
                    内容=新的StringContent(上传成功)
                };
            }
        }
        返回响应;
    }


解决方案

  

下面是完整的上传测试用例:


布局结果
为了简便起见,我将只要求一块标记

 <!DOCTYPE HTML>
< HTML和GT;
< HEAD>
    <! - 在这里你可以拥有所有头子标签(元,标题,CSS相关链接REF标签和其他一些像近代化脚本和其他标记,需要App) - GT;
< /头>
<身体GT;
    <! - 导航栏与页面标题标题 - >    < D​​IV CLASS =箱体内容>
        @RenderBody()
        <! - 页脚 - >
    < / DIV>    <脚本SRC =〜/脚本/ jQuery的-1.10.2.min.js>< / SCRIPT>
    <! - 嵌入全球其他脚本在这里 - >
    @RenderSection(脚本,FALSE)
< /身体GT;
< / HTML>

UploadFilePage.css

  {体
        填充:30像素;
    }    表格{
        显示:块;
        保证金:20像素自动;
        背景:#eee;
        边界半径:10px的;
        填充:15px的;
    }    .progress {
        位置:相对;
        宽度:400像素;
        边框:1px的固体#ddd;
        填充:1px的;
        边界半径:的3px;
    }    {的.bar
        背景颜色:#B4F5B4;
        宽度:0%;
        高度:20像素;
        边界半径:的3px;
    }    。百分 {
        位置:绝对的;
        显示:inline-block的;
        顶部:的3px;
        左:48%;
    }

UploadFile查看标记

  @ {
    ViewBag.Title =上传演示;
}
<链接HREF =〜/内容/ UploadFilePage.css的rel =stylesheet属性类型=文/ CSS/>
< H2>上传DEMO< / H><形式的行动=/ API /上传/ UploadFile的方法=POSTENCTYPE =的multipart / form-data的>
    <输入类型=文件名称=UploadedFile的/>< BR />
    <输入类型=提交值=上传文件到服务器/>
< /表及GT;
< D​​IV CLASS =进步>
    < D​​IV CLASS =酒吧>< / DIV>
    < D​​IV CLASS =百分比大于0%LT; / DIV>
< / DIV>
< D​​IV ID =状态>< / DIV>
@section脚本{
    &所述; SCRIPT SRC =htt​​p://malsup.github.com/jquery.form.js>&下; /脚本>
    <脚本>
        (函数(){
            VAR栏= $('吧'),百分比= $('%左右。),状态= $('#状态');            $('形式')。当作ajaxForm({
                beforeSend:功能(){
                    status.empty();
                    变种percentVal =0%;
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                上传进度:函数(事件,位置,共有PERCENTCOMPLETE){
                    VAR percentVal = PERCENTCOMPLETE +'%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                成功:函数(响应){
                    VAR percentVal =100%;
                    bar.width(percentVal)
                    percent.html(percentVal);
                    警报(响应); //它只是单元测试,pleae您的测试后删除。因为我们在网页上展示的状态,则不需要此警报。
                },
                错误:功能(XHR){
                    status.html(xhr.responseText ||'错误 - 文件上传失败。');
                },
                完成:功能(XHR){
                    status.html(xhr.responseText);
                }
            });        })();
    < / SCRIPT>
}

API控制器结果
为了避免confustion,我申请类似的逻辑你在API控制器动作

 使用System.IO;
使用System.Linq的;
使用System.Net;
使用System.Net.Http;
使用的System.Web;
使用System.Web.Http;命名空间TestCases.MVC.Controllers
{
    公共类UploadController:ApiController
    {
        [HttpPost]
        公众的Htt presponseMessage UploadFile()
        {
            HTT presponseMessage响应= NULL;
            如果(HttpContext.Current.Request.Files.AllKeys.Any()){
                HttpContext.Current.Response.ContentType =text / html的;
                VAR httpPostedFile = HttpContext.Current.Request.Files [UploadedFile的];                如果(httpPostedFile!= NULL){                    //验证上传的图片(可选)                    //获取完整的文件路径
                    变种uploadFilesDir = HttpContext.Current.Server.MapPath(〜/ UPLOADEDFILES);
                    如果(!Directory.Exists(uploadFilesDir)){
                        Directory.CreateDirectory(uploadFilesDir);
                    }
                    VAR fileSavePath = Path.Combine(uploadFilesDir,httpPostedFile.FileName);                    //保存上传的文件为UPLOADEDFILES文件夹中
                    httpPostedFile.SaveAs(fileSavePath);                    响应=新的Htt presponseMessage(的HTTPStatus code.Created){
                        内容=新的StringContent(上传成功)
                    };
                }
            }
            返回响应;
        }    }
}

I am having a client HTML application and an Asp.net WebAPI as the server application. I am having a scenario that I have to make a form submission and as part of Form Submit I need to post the form data to database. This is working for me, but how can the client app knows about the success or Failure status of the DB operation which is happening in a different domain. I have tried to return HttpResponseMessage object to the client but my entire HTML page got rewrite with the status which I am returning from the server. Is there any ways there for this to check a particular status alone rather than rewriting the entire HTML with the response getting from the server API application so that I will have lot more control in the client app?

Client Code for Submitting the Form:

   function ValidateFileAndSubmit() {
        var myForm = $("#form1");
        //UploadFiles();
        var rootServicePath = config.rootURL;
        var path = rootServicePath + 'api/Upload/UploadFile';

        myForm.attr('action', path);
        myForm.submit();

    }

Web Api code where I am access the POST call:

[HttpPost]
    public HttpResponseMessage UploadFile()
    {
        HttpResponseMessage response = null;
        if (HttpContext.Current.Request.Files.AllKeys.Any())
        {
            HttpContext.Current.Response.ContentType = "text/HTML";
            var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

            if (httpPostedFile != null)
            {

                // Validate the uploaded image(optional)

                // Get the complete file path
                var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);

                // Save the uploaded file to "UploadedFiles" folder
                httpPostedFile.SaveAs(fileSavePath);

                response = new HttpResponseMessage(HttpStatusCode.Created)
                {
                    Content = new StringContent("Uploaded Successfully")
                };
            }
        }
        return response;
    }

解决方案

Here is the full upload test case:

Layout
For brevity I'm putting only required piece of Markup

<!DOCTYPE html>
<html>
<head>
    <!-- Here you'll have all head child tags(meta, title, CSS related links ref tags and some other like modernizer scripts and other tags that required for app)-->
</head>
<body>
    <!--navbar with Page heading title-->

    <div class="container body-content">
        @RenderBody()
        <!--footer-->
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <!--embed other global scripts here-->
    @RenderSection("scripts", false)
</body>
</html>

UploadFilePage.css

    body {
        padding: 30px;
    }

    form {
        display: block;
        margin: 20px auto;
        background: #eee;
        border-radius: 10px;
        padding: 15px;
    }

    .progress {
        position: relative;
        width: 400px;
        border: 1px solid #ddd;
        padding: 1px;
        border-radius: 3px;
    }

    .bar {
        background-color: #B4F5B4;
        width: 0%;
        height: 20px;
        border-radius: 3px;
    }

    .percent {
        position: absolute;
        display: inline-block;
        top: 3px;
        left: 48%;
    }

UploadFile View Markup

@{
    ViewBag.Title = "Upload Demo";
}
<link href="~/Content/UploadFilePage.css" rel="stylesheet" type="text/css" />
<h2>Upload DEMO</h2>

<form action="/api/upload/UploadFile" method="post" enctype="multipart/form-data">
    <input type="file" name="UploadedFile" /><br />
    <input type="submit" value="Upload File to Server" />
</form>
<div class="progress">
    <div class="bar"></div>
    <div class="percent">0%</div>
</div>
<div id="status"></div>
@section scripts   {
    <script src="http://malsup.github.com/jquery.form.js"></script>
    <script>
        (function () {
            var bar = $('.bar'), percent = $('.percent'), status = $('#status');

            $('form').ajaxForm({
                beforeSend: function () {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                success: function (response) {
                    var percentVal = '100%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                    alert(response);//its just for unit testing, pleae remove after your testing. This alert is not required as we are showing status on the page.
                },
                error: function (xhr) {
                    status.html(xhr.responseText || 'Error - File upload failed.');
                },
                complete: function (xhr) {
                    status.html(xhr.responseText);
                }
            });

        })();
    </script>
}

API Controller
To avoid confustion, I applied similar logic you have in the api-controller-action

using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace TestCases.MVC.Controllers
{
    public class UploadController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage UploadFile()
        {
            HttpResponseMessage response = null;
            if (HttpContext.Current.Request.Files.AllKeys.Any()) {
                HttpContext.Current.Response.ContentType = "text/HTML";
                var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];

                if (httpPostedFile != null) {

                    // Validate the uploaded image(optional)

                    // Get the complete file path
                    var uploadFilesDir = HttpContext.Current.Server.MapPath("~/UploadedFiles");
                    if (!Directory.Exists(uploadFilesDir)) {
                        Directory.CreateDirectory(uploadFilesDir);
                    }
                    var fileSavePath = Path.Combine(uploadFilesDir, httpPostedFile.FileName);

                    // Save the uploaded file to "UploadedFiles" folder
                    httpPostedFile.SaveAs(fileSavePath);

                    response = new HttpResponseMessage(HttpStatusCode.Created) {
                        Content = new StringContent("Uploaded Successfully")
                    };
                }
            }
            return response;
        }

    }
}

这篇关于如何获得响应的状态,而我们提交一个表单的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆