简体   繁体   English

如何使用C#在MVC5中仅执行一次代码的某些部分?

[英]How to execute certain part of code just once in MVC5 using C#?

I have a view where user chooses a photo from his/her computer and uploads it to Flickr. 我有一个视图,用户可以从他/她的计算机中选择一张照片并将其上传到Flickr。 The point is that once the button is clicked, it redirects to Flickr which asks for authorization, and once authorization process is finished it redirects back to that action method. 关键是单击该按钮后,它将重定向到要求授权的Flickr,并且一旦授权过程完成,它将重定向回到该操作方法。 Below you can see some code to make it more clear. 在下面,您可以查看一些代码以使其更加清晰。

Test.cshtml: Test.cshtml:

@using (Html.BeginForm("UploadToFlickr", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <fieldset>
        <input type="file" name="file" />
        <input type="submit" value="Upload!" />
    </fieldset>
}

HomeController.cs: HomeController.cs:

public class HomeController : Controller
{
        public static string tmpFilePath, filename, path;
        // some other methods...

        public ActionResult UploadToFlickr(HttpPostedFileBase file, FormCollection form)
        {
            tmpFilePath = Server.MapPath("~/App_Data/Uploads/Pictures");

            if (file == null || file.ContentLength == 0)
            {
                return RedirectToAction("Index");
            }

            filename = Path.GetFileName(file.FileName);
            path = Path.Combine(tmpFilePath, filename);

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }

            file.SaveAs(path);

            if (Request.QueryString["oauth_verifier"] != null && Session["RequestToken"] != null)
            {
                // Flickr relevant code...

                string photoId = flickr.UploadPicture(path, "Test picture");
            }
            else
            {
                // Flickr relevant code...

                string url = flickr.OAuthCalculateAuthorizationUrl(token.Token, AuthLevel.Write);

                Response.Redirect(url);
            }

            return View("Test");
        }

So the point is that, I have already defined tmpFilePath, filename and path variables as static, as you can see. 关键是,您已经看到,我已经将tmpFilePath,文件名和路径变量定义为静态。 When I click the upload button, at at first it calls the UploadToFlickr method, which executes the initial lines of code, and then enters into else, which redirects the app to Flickr authorization, then when I click authorize, it again generates a URL that includes the UploadToFlickr method, which call that method again, but this time the file parameter is null, and it enters into the part return RedirectToAction("Index"); 当我单击上载按钮时,首先它会调用UploadToFlickr方法,该方法执行初始代码行,然后输入else,将应用程序重定向到Flickr授权,然后当我单击授权时,它再次生成一个URL包括UploadToFlickr方法,该方法再次调用该方法,但是这次file参数为null,并且它进入部分return RedirectToAction("Index"); . Is there any way, how can I solve this? 有什么办法,我该如何解决? I need the part until the if case to be executed just once, only when the button is clicked. 仅在单击按钮时,才需要if案例仅执行一次的部分。 Not the second time when I'm redirected from Flickr. 这不是我第二次从Flickr重定向时。

The callback is most likely using an HTTP GET rather than an HTTP POST. 回调很可能使用HTTP GET而不是HTTP POST。 Split your actions into two methods and decorate the one you post to with [HttpPost] and the callback method with [HttpGet] . 将您的操作分为两种方法,并使用[HttpPost]装饰您发布到的方法,并使用[HttpGet]装饰回调方法。 The [HttpPost] method should only be called when the user hits the upload button (since the FormMethod is set to Post), so that method should only be responsible for validating the file they uploaded and passing it along to Flickr. 仅当用户单击上传按钮时才调用[HttpPost]方法(因为FormMethod设置为Post),因此该方法仅应负责验证他们上传的文件并将其传递给Flickr。 After Flickr has done it's thing, if it is calling back to your app, it should call the [HttpGet] method, where you redirect or do whatever else you want to do. Flickr完成操作后,如果它要回调您的应用程序,则应调用[HttpGet]方法,您可以在其中重定向或执行您想执行的其他任何操作。 I'm not familiar with the Flickr API but this should get you close. 我不熟悉Flickr API,但这应该可以让您接近。

Keep in mind that uploading your image and getting a callback from Flickr are two completely separate requests to your application. 请记住,上传图像和从Flickr获取回调是对应用程序的两个完全独立的请求。 You need to determine what to do based on the HTTP request method, provided parameters, etc. for both unique requests. 您需要基于HTTP请求方法,所提供的参数等来确定两个唯一请求的处理方式。

public class HomeController : Controller
{
    public static string tmpFilePath, filename, path;
    // some other methods...

    [HttpGet]
    public ActionResult UploadToFlickr()
    {
        // This method will probably get called back by Flickr

        return RedirectToAction("Index");
    }

    [HttpPost]
    public ActionResult UploadToFlickr(HttpPostedFileBase file, FormCollection form)
    {
        // This method will only be called when the user clicks the upload button

        tmpFilePath = Server.MapPath("~/App_Data/Uploads/Pictures");

        if (file == null || file.ContentLength == 0)
        {
            // No file was provided...show validation errors or something
        }

        filename = Path.GetFileName(file.FileName);
        path = Path.Combine(tmpFilePath, filename);

        if (System.IO.File.Exists(path))
        {
            System.IO.File.Delete(path);
        }

        file.SaveAs(path);

        if (Request.QueryString["oauth_verifier"] != null && Session["RequestToken"] != null)
        {
            // Flickr relevant code...

            string photoId = flickr.UploadPicture(path, "Test picture");
        }
        else
        {
            // Flickr relevant code...

            string url = flickr.OAuthCalculateAuthorizationUrl(token.Token, AuthLevel.Write);

            Response.Redirect(url);
        }

        return View("Test");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM